package com.example.testnetwork;
import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import io.reactivex.functions.Consumer;


/**
 * 启动一个Service：KeepLiveService
 */
public class MainActivity extends AppCompatActivity {
    String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        checkPermissions();

    }

    @Override
    protected void onStart() {
        startService();
        super.onStart();
    }

    private void checkPermissions() {

        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .requestEach(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                       )
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            Log.i(TAG, "accept");
                        }
                        else if (permission.shouldShowRequestPermissionRationale) {
                                Log.i(TAG,"shouldShowRequestPermissionRationale");
                        }
                        else {

                        }
                    }
                });
    }
    /**
     * 启动后台服务
     */
    public void startService()
    {
        if (Build.VERSION.SDK_INT >= 26) {
            Intent bleSvcIntent = new Intent(this, KeepLiveService.class);
            this.startForegroundService(bleSvcIntent);
        } else {
            Intent bleSvcIntent = new Intent(this, KeepLiveService.class);
            this.startService(bleSvcIntent);
        }
    }
}
